package com.wei.miaosha.controller;

import com.wei.miaosha.domain.MiaoshaUser;
import com.wei.miaosha.redis.GoodsKey;
import com.wei.miaosha.redis.RedisService;
import com.wei.miaosha.result.Result;
import com.wei.miaosha.service.GoodsService;
import com.wei.miaosha.service.MiaoshaUserService;
import com.wei.miaosha.util.LogUtils;
import com.wei.miaosha.vo.GoodsDetailVo;
import com.wei.miaosha.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Weizichen on 2018/8/11.
 * desc:商品页面控制层
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    private static Logger logger = LogManager.getLogger("GoodsController");
    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    ApplicationContext applicationContext;

    /**
     * Qps1:691  Qps2:2700
     * 1000*10
     */
    @RequestMapping(value = "/to_list", produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user
                     /*  @CookieValue(value = MiaoshaUserService.COOKIE_NAME_TOKEN, required = false) String cookieToken,
                       @RequestParam(value = MiaoshaUserService.COOKIE_NAME_TOKEN, required = false) String paramToken*/) {
/*
        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
            return "login";
        }
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        MiaoshaUser user = miaoshaUserService.getByToken(token, response);*/
        model.addAttribute("user", user);
        //缓存中去取
        String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        //return "goods_list";

        //手动渲染
        SpringWebContext cx = new SpringWebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", cx);
        if (!StringUtils.isEmpty(html)) {
            //保存缓存中去
            redisService.set(GoodsKey.getGoodsList, "", html);
        }
        LogUtils.infoLog(logger, " " + "-" + " " + "-" + " " + "success" + " " + "商品列表,网页静态化");
        return html;
    }

    @RequestMapping(value = "/to_detail2/{goodsId}", produces = "text/html")
    @ResponseBody
    public String detail2(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user,
                          @PathVariable("goodsId") long goodsId) {
        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goodsVo", goodsVo);
        //秒杀开始时间
        long start = goodsVo.getStartDate().getTime();
        //秒杀结束时间
        long end = goodsVo.getEndDate().getTime();
        //现在时间
        long now = System.currentTimeMillis();
        //倒计时
        int remainSeconds = 0;
        int miaoShaFlag = 0;
        if (now < end && now > start) {
            //秒杀进行中
            miaoShaFlag = 1;
            remainSeconds = 0;
        } else if (now > end) {
            //秒杀结束
            miaoShaFlag = 2;
            remainSeconds = -1;
        } else {
            //秒杀未开始
            miaoShaFlag = 0;
            remainSeconds = (int) (start - now) / 1000;
        }
        model.addAttribute("miaoShaFlag", miaoShaFlag);
        model.addAttribute("remainSeconds", remainSeconds);
        // return "goods_detail";
        //缓存中去取
        String html = redisService.get(GoodsKey.getGoodsDetail, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        //手动渲染
        SpringWebContext cx = new SpringWebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", cx);
        if (!StringUtils.isEmpty(html)) {
            //保存缓存中去
            redisService.set(GoodsKey.getGoodsDetail, "", html);
        }
        return html;
    }


    @RequestMapping(value = "/detail/{goodsId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user,
                                        @PathVariable("goodsId") long goodsId) {

        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        //秒杀开始时间
        long start = goodsVo.getStartDate().getTime();
        //秒杀结束时间
        long end = goodsVo.getEndDate().getTime();
        //现在时间
        long now = System.currentTimeMillis();
        //倒计时
        int remainSeconds = 0;
        int miaoShaFlag = 0;
        if (now < end && now > start) {
            //秒杀进行中
            miaoShaFlag = 1;
            remainSeconds = 0;
        } else if (now > end) {
            //秒杀结束
            miaoShaFlag = 2;
            remainSeconds = -1;
        } else {
            //秒杀未开始
            miaoShaFlag = 0;
            remainSeconds = (int) (start - now) / 1000;
        }
        GoodsDetailVo vo = new GoodsDetailVo();
        vo.setGoods(goodsVo);
        vo.setMiaoShaFlag(miaoShaFlag);
        vo.setRemainSeconds(remainSeconds);
        vo.setUser(user);
        LogUtils.infoLog(logger, " " + "-" + " " + "-" + " " + "success" + " " + "商品详情");
        return Result.success(vo);
    }

}
